<script setup lang="tsx">
import { PropType, ref, unref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { uploadFileApi } from '@/api/common'
import { contentSaveApi, contentUpdateApi, contentCategoryListApi } from '@/api/college'
import { ContentItem, ContentCategoryItem } from '@/api/college/types'
import { useValidator } from '@/hooks/web/useValidator'
import { ContentPortDict, dictToList } from '@/utils/dict'
import { useI18n } from '@/hooks/web/useI18n'

const { t } = useI18n()
const { required, lengthRange } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<ContentItem>,
    default: () => undefined
  }
})

const uploadFile = async (file: File, insertFn: any) => {
  const formData = new FormData()
  formData.append('file', file)
  const res = await uploadFileApi(5, formData)
  if (res.code === 200) {
    insertFn(res.data)
  } else {
    res.message && ElMessage.error(res.message)
  }
}

const isDisabled = ref(true)

const categoryList = ref<ContentCategoryItem[]>([])
const getCategoryList = async (contentPort: number) => {
  if (contentPort) {
    isDisabled.value = false
  }
  console.log(contentPort, 'contentPort')
  const res = await contentCategoryListApi({ contentPort: contentPort })
  if (res.code === 200) {
    categoryList.value = res.data.list || []
  }
  setSchema([
    {
      field: 'categoryId',
      path: 'componentProps.options',
      value: unref(
        categoryList.value.map((it: ContentCategoryItem) => ({
          label: it.categoryName,
          value: it.id
        }))
      )
    }
  ])
}

const formSchema = reactive<FormSchema[]>([
  {
    field: 'title',
    label: t('college.articleTitle'),
    colProps: {
      span: 24
    },
    component: 'Input',
    componentProps: {
      placeholder: t('college.articleTitleHint')
    }
  },
  {
    field: 'contentPort',
    label: t('college.contentPort'),
    colProps: {
      span: 24
    },
    component: 'Select',
    componentProps: {
      options: dictToList(ContentPortDict),
      on: {
        change: async (val: number) => {
          if (val) {
            isDisabled.value = false
          } else {
            isDisabled.value = true
          }
          getCategoryList(val).then(() => {
            setValues({
              categoryId: null
            })
          })
        }
      }
    }
  },
  {
    field: 'categoryId',
    label: t('college.articleCategory'),
    component: 'Select',
    componentProps: {
      disabled: isDisabled,
      options: categoryList.value.map((it: ContentCategoryItem) => ({
        label: it.categoryName,
        value: it.id
      }))
    }
  },
  {
    field: 'contentSort',
    label: t('college.sortLabel'),
    colProps: {
      span: 24
    },
    component: 'Input',
    componentProps: {
      placeholder: t('college.sortHint')
    }
  },
  {
    field: 'contentType',
    label: '内容类型',
    colProps: {
      span: 24
    },
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: 'URL',
          value: 1
        },
        {
          label: '富文本',
          value: 0
        }
      ],
      on: {
        change: (val: number) => {
          // 切换后清空内容
          setValues({
            details: ''
          })
          if (val === 1) {
            setSchema([
              {
                field: 'details',
                path: 'label',
                value: 'URL链接'
              },
              {
                field: 'details',
                path: 'component',
                value: 'Input'
              },
              {
                field: 'details',
                path: 'componentProps',
                value: {
                  placeholder: '请输入URL链接',
                  type: 'textarea',
                  rows: 5
                }
              }
            ])
          } else {
            setSchema([
              {
                field: 'details',
                path: 'label',
                value: '文章详情'
              },
              {
                field: 'details',
                path: 'component',
                value: 'Editor'
              },
              {
                field: 'details',
                path: 'componentProps',
                value: {
                  editorConfig: {
                    MENU_CONF: {
                      uploadImage: {
                        // 自定义上传
                        customUpload: uploadFile
                      },
                      uploadVideo: {
                        customUpload: uploadFile
                      }
                    }
                  }
                }
              }
            ])
          }
        }
      }
    }
  },
  {
    field: 'details',
    label: props.currentRow && props.currentRow.contentType === 0 ? '文章详情' : 'URL链接', // 默认URL
    colProps: {
      span: 24
    },
    component: props.currentRow && props.currentRow.contentType === 0 ? 'Editor' : 'Input', // 默认URL
    componentProps:
      props.currentRow && props.currentRow?.contentType === 0 // 默认URL
        ? {
            editorConfig: {
              MENU_CONF: {
                uploadImage: {
                  // 自定义上传
                  customUpload: uploadFile
                },
                uploadVideo: {
                  customUpload: uploadFile
                }
              }
            }
          }
        : {
            placeholder: '请输入URL链接',
            type: 'textarea',
            rows: 5
          }
  }
])

const rules = reactive({
  title: [required(), lengthRange({ min: 2, max: 30 })],
  contentPort: [required(t('common.selectText'))],
  categoryId: [required(t('common.selectText'))],
  contentType: [required()],
  details: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const createArticle = async (data: any) => {
  const param: ContentItem = {
    title: data.title,
    contentPort: data.contentPort,
    categoryId: data.categoryId,
    contentSort: +data.contentSort || 0,
    contentType: data.contentType,
    details: data.details
  }
  const res = await contentSaveApi(param)
  return res.code === 200
}

const updateArticle = async (data: any) => {
  const param: ContentItem = {
    id: data.id,
    title: data.title,
    contentPort: data.contentPort,
    categoryId: data.categoryId,
    contentSort: +data.contentSort || 0,
    contentType: data.contentType,
    details: data.details
  }
  const res = await contentUpdateApi(param)
  return res.code === 200
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.contentSort > 1000000 || formData.contentSort < 0) {
      ElMessage.error('排序范围为0到1000000之间')
      return
    }
    if (formData.id) {
      // 修改
      return updateArticle(formData)
    } else {
      // 新增
      return createArticle(formData)
    }
  }
}

// 重置Form
const reset = async () => {
  const elForm = await getElFormExpose()
  setValues({ id: '' })
  elForm?.resetFields()
}

const formData = async () => await getFormData()

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) {
      setValues({
        contentType: 1 // 默认URL
      })
      return
    }
    getCategoryList(currentRow.contentPort)
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  formData,
  reset,
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
